package org.example.service;

import org.example.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQMessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.application.name}")
    private String serverId;

    public void sendMessageToUser(String userId, Object message) {
        String routingKey = RabbitMQConfig.WEBSOCKET_ROUTING_KEY_PREFIX + userId;
        rabbitTemplate.convertAndSend(RabbitMQConfig.WEBSOCKET_EXCHANGE, routingKey, message);
    }

    public void sendMessageToServer(String targetServerId, Object message) {
        String routingKey = RabbitMQConfig.WEBSOCKET_ROUTING_KEY_PREFIX + "server." + targetServerId;
        rabbitTemplate.convertAndSend(RabbitMQConfig.WEBSOCKET_EXCHANGE, routingKey, message);
    }

    public void broadcastMessage(Object message) {
        String routingKey = RabbitMQConfig.WEBSOCKET_ROUTING_KEY_PREFIX + "broadcast";
        rabbitTemplate.convertAndSend(RabbitMQConfig.WEBSOCKET_EXCHANGE, routingKey, message);
    }
}